﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIA.Configurators;

namespace SIA.HwAccess.PLCSiemens
{
    /// <summary>La classe rappresenta un byte di un PLC Siemens</summary>
    public class S7Byte : S7Signal, IIntegerSignal
    {
        private Byte _value;

        public override object Value { get { return IntValue; } set { IntValue = (int)value; } }
        public int IntValue
        {
            get { return (int)_value; }
            set
            {
                
                if (_value != (Byte)value)
                {
                    _value = (Byte)value;                    
                    if (this.ValueChange != null) this.ValueChange(this);
                }

                _connection.requestWriteData(_address, 0, _value);
            }
        }

        /// <summary>Costruttore standard</summary>
        /// <param name="signalProperty"></param>
        /// <param name="connection"></param>
        public S7Byte(IDictionaryProperty signalProperty, IHwConnection connection)
            : base(signalProperty, connection)
        {
            _connection.DataArrived += new ConnectionDataEvent(_connection_DataArrived);
        }

        /// <summary>Gestione evento nuovi dati arrivati dalla connessione</summary>
        /// <param name="conn"></param>
        void _connection_DataArrived(IHwConnection conn, IRawData data)
        {
            //Verifico la presenza della chiave
            if (data.ContainsKey(_address.DataKey))
            {
                Byte oldValue = _value;
                _value = data[_address.DataKey][_address.StartByte];
                if (oldValue != _value)
                    if (this.ValueChange != null) this.ValueChange(this);
            }
            else
                SIA.Messages.MessageManager.sendMessage(this, "Dati non presenti nella connessione", SIA.Messages.eMessageType.DEBUG);
        }

        public override event SignalEvent ValueChange;
    }
}
